<template>
	<view class="com-qrcode"
	:class="{'com-qrcode-hidden': !visible}"
	:style="{
		'width': visible ? width + 'px' : 0,
		'height': visible ? height + 'px' : 0
	}"
	:data-text="text"
	:data-width="width"
	:data-height="height"
	:data-colorDark="colorDark"
	:data-colorLight="colorLight"
	:data-correctLevel="correctLevel"
	
	:start="start" :change:start="qrcodeRender.makeCode"
	:temp="temp" :change:temp="qrcodeRender.makeImage"></view>
</template>

<script>
	export default {
		props: {
			//是否主动显示二维码
			visible: {
				type: Boolean,
				default: true
			},
			//主动生成二维码
			auto: {
				type: Boolean,
				default: true
			},
			//二维码内容
			text: {
				type: String,
				default: ''
			},
			//生成二维码宽度
			width: {
				type: [Number, String],
				default: 128
			},
			//生成二维码高度
			height: {
				type: [Number, String],
				default: 128
			},
			//二维码黑色主体颜色
			colorDark: {
				type: String,
				default: '#000000'
			},
			//二维码白色主体颜色
			colorLight: {
				type: String,
				default: '#ffffff'
			},
			//生成二维码精度
			correctLevel: {
				type: [Number, String],
				default: 2
			}
		},
		data () {
			return {
				ready: false,//渲染层是否已经准备好了
				start: -1,
				temp: -1,
				successCall: null,//成功回调
				failCall: null,//失败回调
				completeCall: null//失败回调
			}
		},
		methods: {
			before ({success, fail, complete}) {
				if ( this.start == 1 || this.temp == 1 ) {
					const err = {errCode: 1, errMsg: '生成二维码失败，请等待上个操作结束'}
					fail && fail(err)
					complete && complete(err)
					return false
				}
				this.successCall = success
				this.failCall = fail
				this.completeCall = complete
				return true
			},
			make (data) {
				const result = this.before(data)
				if ( result ) {
					this.start = -1
					this.$nextTick(() => {
						this.start = 1
					})
				}
			},
			//生成二维码临时路径
			toTempFilePath (data) {
				const result = this.before(data)
				if ( result ) {
					this.temp = -1
					this.$nextTick(() => {
						this.temp = 1
					})
				}
			},
			//生成二维码回调
			makeCall (res) {
				this.start = -1
				if ( res.errCode == 0 ) this.successCall && this.successCall(res)
				else this.failCall && this.failCall(res)
				this.completeCall && this.completeCall(res)
				this.$emit('maked', res)
			},
			//生成临时图片路径回调
			tempCall (res) {
				this.temp = -1
				if ( res.errCode == 0 ) this.successCall && this.successCall(res)
				else this.failCall && this.failCall(res)
				this.completeCall && this.completeCall(res)
			},
			callReady () {
				this.ready = true
				this.$emit('ready')
				if ( this.auto && this.text ) this.make({})
			}
		},
		watch: {
			text (newVal) {
				if ( this.ready && this.auto ) this.make({})
			}
		}
	}
</script>

<!-- #ifdef H5 | APP-VUE -->
<script lang="renderjs" type="module" module="qrcodeRender">
	import QRCode from "./qrcode.js"
	export default {
		data () {
			return {
				dom: null,
				qrcode: null
			}
		},
		mounted () {
			this.dom = document.getElementsByClassName('com-qrcode')[0]
			this.callMethod('callReady', true)//通知逻辑层，渲染层已做好准备
		},
		methods: {
			makeCode (newVal) {
				if ( newVal == 1 && this.dom ) {
					const text = this.getData('text')
					if ( text ) {
						try{
							this.dom.innerHTML = ''
							this.qrcode = new QRCode(this.dom, {
							    text: text,
							    width: this.getData('width'),
							    height: this.getData('height'),
							    colorDark : this.getData('colorDark'),
							    colorLight : this.getData('colorLight'),
							    correctLevel : this.getData('correctLevel') || QRCode.CorrectLevel.H
							});
							this.callMethod('makeCall', {
								errCode: 0,
								errMsg: '生成二维码成功'
							})
						}catch(e){
							var errMsg = '生成内容字符太长：' +  e.toString() + '。请增加二维码精度（correctLevel）'
							this.dom.innerHTML = `
								<div style="position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);font-size:12px;color:${this.getData('colorDark')}">${errMsg}</div>
							`
							this.callMethod('makeCall', {
								errCode: 1,
								errMsg
							})
						}
					} else {
						this.callMethod('makeCall', {
							errCode: 2,
							errMsg: '请传入二维码内容'
						})
					}
				}
			},
			makeImage (newVal) {
				if ( newVal == 1 && this.dom ) {
					if ( this.qrcode ) {
						const canvas = this.dom.firstChild
						canvas.toBlob(blob => {
							const base64 = canvas.toDataURL('image/png')
							this.callMethod('tempCall', {
								errCode: 0,
								errMsg: 'ok',
								data: {
									blob,
									base64
								}
							})
						})
						
					} else {
						this.callMethod('tempCall', {
							errCode: 2,
							errMsg: '没有发现二维码对象，生成临时图片路径失败'
						})
					}
				}
			},
			getData (name) {
				if ( ['width', 'height', 'correctLevel'].includes(name) ) {
					return parseInt(this.dom.getAttribute('data-' + name))
				} else {
					return this.dom.getAttribute('data-' + name)
				}
			},
			callMethod (name, args) {
				// #ifndef H5
				this.$ownerInstance.callMethod(name, args)
				// #endif
				// #ifdef H5
				this[name](args)
				// #endif
			}
		}
	}
</script>
<!-- #endif -->

<style>
	.com-qrcode-hidden {
		visibility: hidden;
		width: 0;
		height: 0;
	}
</style>